package com.dnjn.mes.biz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.mes.biz.assist.ext.Wrapperz;
import com.dnjn.mes.biz.domain.MesAssembly;
import com.dnjn.mes.biz.domain.MesEquipment;
import com.dnjn.mes.biz.domain.MesWorkpiece;
import com.dnjn.mes.biz.enums.BoolType;
import com.dnjn.mes.biz.service.IMesEquipmentService;
import com.dnjn.mes.biz.service.IMesWorkpieceService;
import com.dnjn.mes.common.core.controller.BaseController;
import com.dnjn.mes.common.core.domain.AjaxResult;
import com.dnjn.mes.common.core.domain.entity.SysUser;
import com.dnjn.mes.common.core.page.TableDataInfo;
import com.dnjn.mes.common.utils.JpPinyinUtil;
import com.dnjn.mes.common.utils.StringUtils;
import com.dnjn.mes.common.utils.poi.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>
 * 工件 零部件 前端控制器
 * </p>
 *
 * @author Amber
 * @since 2023-07-26
 */
@Tag(name = "mes workpiece 零部件", description = "零部件")
@RestController
@RequestMapping("/biz/mesWorkpiece")
public class MesWorkpieceController extends BaseController {

    @Autowired
    protected IMesWorkpieceService baseService;

    @Autowired
    private IMesEquipmentService equipmentService;


    @GetMapping("/getByCrumbNames")
    public AjaxResult getByCrumbNames(String equipmentName, String assemblyName, String workpieceName) {
        return success(baseService.queryBy(equipmentName, assemblyName, workpieceName));
    }


    @PostMapping("/page")
    public AjaxResult page(@RequestBody MesWorkpiece domain, @RequestParam(defaultValue = "1") Integer current,
                           @RequestParam(defaultValue = "10") Integer size,
                           @RequestParam(defaultValue = "workpiece_id") String orderByDesc, @RequestParam(value = "searchKey", required = false) @Parameter(description = "workpieceName") String searchKey) {
        Page<MesWorkpiece> page = Page.of(current, size);
        //Page<MesWorkpiece> list = baseService.page(page, Wrappers.<MesWorkpiece>query(domain).orderByDesc(orderByDesc));
        QueryWrapper<MesWorkpiece> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc(orderByDesc);
        if (StringUtils.isNotEmpty(searchKey)) {
            queryWrapper.like("workpiece_name", searchKey);
        }
        Page<MesWorkpiece> list1 = baseService.page(page, queryWrapper);
        return success(list1);
    }

    @Parameters({
            @Parameter(name = "assemblyId", description = "assemblyId")
    })
    @PostMapping("/export")
    public void export(HttpServletResponse response, MesWorkpiece domain) {
        //List<MesWorkpiece> list = baseService.list(Wrappers.query(domain));
        QueryWrapper<MesWorkpiece> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("assembly_id", domain.getAssemblyId());
        List<MesWorkpiece> list = baseService.list(queryWrapper);
        ExcelUtil<MesWorkpiece> util = new ExcelUtil<MesWorkpiece>(MesWorkpiece.class);
        util.exportExcel(response, list, "参数数据");
    }

    @PostMapping("importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<MesWorkpiece> util = new ExcelUtil<MesWorkpiece>(MesWorkpiece.class);
        List<MesWorkpiece> list = util.importExcel(file.getInputStream());
        String message = baseService.importData(list, updateSupport);
        return success(message);
    }

    /*
            {
            "assemblyId": 1693436913676636161,
          "workpieceName": "1",
          "workpieceNo": "1",
          "workpieceImage": "1",
          "maintainDuration": 1,
          "maintainType": "1",
          "remindPct": 1,
          "remindMessage": "1",
          "warningPct": 1,
          "warningMessage": "1",
          "maintainStepUrl": "1",
        }
    */
    /*@Parameters({
            @Parameter(name = "assemblyId", description = "assemblyId"),
            @Parameter(name = "workpieceName", description = "名称"),
            @Parameter(name = "workpieceNo", description = "规格型号"),
            @Parameter(name = "workpieceImage", description = "图片名称"),
            @Parameter(name = "maintainDuration", description = "寿命(H)"),
            @Parameter(name = "maintainType", description = "是否根据运行时间倒计时"),
            @Parameter(name = "remindPct", description = "提醒保养时间百分比"),
            @Parameter(name = "remindMessage", description = "提醒保养提示信息"),
            @Parameter(name = "warningPct", description = "警告保养时间百分比"),
            @Parameter(name = "warningMessage", description = "警告保养提示信息"),
            @Parameter(name = "maintainStepUrl", description = "维护保养步骤")
    })*/
    @Operation(summary = "新增工件零部件")
    @PostMapping("/saveWorkPiece")
    public AjaxResult saveWorkPiece(@Validated @RequestBody MesWorkpiece domain) {
        MesEquipment mesEquipment = equipmentService.getOne(Wrapperz.lambdaQuery(MesEquipment.class).eq(MesEquipment::getIsDefault, BoolType.YES));
        domain.setEquipmentId(mesEquipment.getEquipmentId());
        domain.setCreateBy(getUsername());
        //domain.setAssemblyId(assemblyId);
        //获取最大的ordinal值
        Integer ordinal = baseService.getMaxOrdinal();
        ordinal++;
        domain.setOrdinal(ordinal);
        String equipmentName = mesEquipment.getEquipmentName();
        int start = equipmentName.length() - 3, end = equipmentName.length() - 1;
        start = Math.max(start, 0);
        String substring = equipmentName.substring(start, end);
        String pinYin = JpPinyinUtil.changeToTonePinYin(substring);
        //处理图片/步骤    media/paiban/image/2.pngme
        domain.setWorkpieceImage("media/" + pinYin + "/image/" + domain.getWorkpieceImage());
        domain.setMaintainStepUrl("media/" + pinYin + "/docs/" + domain.getMaintainStepUrl());
        return toAjax(baseService.save(domain));
    }

    /**
     * 根据零件id获取零件信息
     */
    @Operation(summary = "根据零件id获取零件信息")
    @GetMapping("/getWorkById/{workpieceId}")
    public AjaxResult getWorkById(@PathVariable Long workpieceId) {
        Assert.notNull(workpieceId, "workpieceId不能为空！");
        return success(baseService.getById(workpieceId));
    }


    /**
     * 获取工件零部件列表根据模块id，有分页+模糊搜索
     */
    @Operation(summary = "获取分页工件零部件列表")
    @PostMapping("/getWorkPage")
    public AjaxResult getWorkPage(@RequestParam(defaultValue = "1") Integer current,
                                  @RequestParam(defaultValue = "10") Integer size,
                                  @RequestParam Long assemblyId,
                                  @RequestParam(required = false)  @Parameter(description = "workpieceName") String searchKey,
                                  @RequestParam(defaultValue = "workpiece_id") String orderByDesc) {
        Assert.notNull(assemblyId, "assemblyId不能为空！");
        PageHelper.startPage(current, size);
        QueryWrapper<MesWorkpiece> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("assembly_id", assemblyId);
        queryWrapper.eq("deleted", "0");
        queryWrapper.like(StringUtils.isNotEmpty(searchKey), "workpiece_name", searchKey);
        queryWrapper.orderByDesc(orderByDesc);
        List<MesWorkpiece> list = baseService.list(queryWrapper);
        PageInfo pageInfo = new PageInfo(list);
        return success(pageInfo);
    }

    /**
     * 获取工件零部件列表根据模块id
     */
    @Operation(summary = "获取工件零部件列表根据模块id")
    @PostMapping("/getWorkPageByAssemblyId")
    public AjaxResult getWorkPageByAssemblyId(@RequestParam Long assemblyId) {
        Assert.notNull(assemblyId, "assemblyId不能为空！");
        QueryWrapper<MesWorkpiece> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("assembly_id", assemblyId);
        queryWrapper.eq("deleted", "0");
        List<MesWorkpiece> list = baseService.list(queryWrapper);
        return success(list);
    }


    /**
     * 修改工件零部件
     */
    /*
            {
            "workpieceId":1693436913676636161,
           "assemblyId": 1693436913676636161,
          "workpieceName": "1",
          "workpieceNo": "1",
          "workpieceImage": "1",
          "maintainDuration": 1,
          "maintainType": "1",
          "remindPct": 1,
          "remindMessage": "1",
          "warningPct": 1,
          "warningMessage": "1",
          "maintainStepUrl": "1",
        }
    */
   /* @Parameters({
            @Parameter(name = "workpieceId", description = "工件id"),
            @Parameter(name = "workpieceName", description = "名称"),
            @Parameter(name = "workpieceNo", description = "规格型号"),
            @Parameter(name = "workpieceImage", description = "图片名称"),
            @Parameter(name = "maintainDuration", description = "寿命(H)"),
            @Parameter(name = "maintainType", description = "是否根据运行时间倒计时"),
            @Parameter(name = "remindPct", description = "提醒保养时间百分比"),
            @Parameter(name = "remindMessage", description = "提醒保养提示信息"),
            @Parameter(name = "warningPct", description = "警告保养时间百分比"),
            @Parameter(name = "warningMessage", description = "警告保养提示信息"),
            @Parameter(name = "maintainStepUrl", description = "维护保养步骤")
    })*/
    @Operation(summary = "修改工件零部件")
    @PutMapping("/editWork")
    public AjaxResult editWork(@Validated @RequestBody MesWorkpiece domain) {
        Long workpieceId = domain.getWorkpieceId();
        Assert.notNull(workpieceId, "workpieceId不能为空！");
        return toAjax(baseService.updateById(domain));
    }

    /**
     * 删除工件零部件
     */
    @Operation(summary = "删除工件零部件")
    @DeleteMapping("/deledtWorkById/{workpieceId}")
    public AjaxResult deledtWorkById(@PathVariable("workpieceId") Long workpieceId) {
        Assert.notNull(workpieceId, "workpieceId不能为空！");
        Long count = baseService.removeWorkById(workpieceId);
        if(count == 1){
            return success("删除成功");
        }else {
            return error("删除失败");
        }
    }


    /**
     * 二级页面-设备维护保养-点击保养完毕，重置零部件倒计时，并记录该次保养时间。新增一条留痕记录到 mes_record_maintain
     */
    @Operation(summary = "零部件保养")
    @PutMapping("/maintenanceWork/{workpieceId}")
    public AjaxResult edit(@PathVariable("workpieceId") Long workpieceId) {
        Assert.notNull(workpieceId, "workpieceId不能为空！");
        boolean flag = baseService.maintenanceWork(workpieceId);
        return toAjax(flag);
    }
}